import React, { useEffect, useRef, useState } from 'react';
import * as CodeMirror from 'codemirror';
import 'codemirror/mode/meta';
import './index.less';

export interface CodeMirrorProps {
  width?: any;
  height?: any;
  options?: any;
  value?: string;
  onLoad?: (editor: any) => void;
}

const RCodeMirror: React.FC<CodeMirrorProps> = function({
  options,
  width = 'auto',
  height,
  value,
  onLoad,
}) {
  const ref = useRef(null);
  const wrapRef = useRef(null);
  const [editor, setEditor] = useState<any>();
  useEffect(() => {
    var editor = CodeMirror.fromTextArea(ref.current as any, options);
    setEditor(editor);
    onLoad && onLoad(editor);
  }, []);

  useEffect(() => {
    if (editor) {
      const h = height || (wrapRef.current as any).offsetHeight;
      editor.setSize(width, h);
    }
  }, [editor, width, height]);

  useEffect(() => {
    if (editor) editor.setValue(value || '');
  }, [editor, value]);

  return (
    <div className="ra-code-mirror" ref={wrapRef}>
      <textarea id="editor" ref={ref} />
    </div>
  );
};

export default RCodeMirror;
